﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.SessionState;  
namespace UcAsp.Net.Web
{
    /// <summary>
    /// UploadFile 的摘要说明
    /// </summary>
    public class UploadFile : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            #region 验证登陆
            if (context.Request.QueryString["Security"] != null)
            {
                string code = Comm.Encrypt.DecodeEncrypt(context.Request.QueryString["Security"].ToString());
                string[] result = code.Split('|');
                DateTime clienttime = DateTime.Parse(result[1]);
                TimeSpan ts = DateTime.Now - clienttime;
                if (ts.Minutes < 10)
                {
                    if (!result[0].Equals(BLL.SysParamBLL.GetParamByName("Security")))
                    {
                        context.Response.ContentType = "text/html";
                        context.Response.ContentType = "text/html";
                        context.Response.Write("nofile");
                        return;
                    }

                }
                else
                {
                    
                    context.Response.ContentType = "text/html";
                    context.Response.Write("nofile");
                    return;
                }
            }
            else
            {
                if (context.Session["Admin"] == null)
                {
                    context.Response.ContentType = "text/html";
                    context.Response.Write("nofile");
                    return;
                }
            }
            #endregion

            if (context.Request.Files.Count > 0)
            {
                HttpPostedFile file = context.Request.Files[0];

                if (file.ContentLength > 200)
                {
                    string yearmonth = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString("00");
                    string save = AppDomain.CurrentDomain.BaseDirectory + System.Configuration.ConfigurationManager.AppSettings["SavePath"] + yearmonth + "/";
                    if (!Directory.Exists(save))
                    {
                        Directory.CreateDirectory(save);
                    }
                    string filename = DateTime.Now.Day.ToString("00") + DateTime.Now.Hour.ToString("00") + DateTime.Now.Month.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + Ext(file.FileName);
                    file.SaveAs(save + filename);
                    if (!IsAllowedExtension(save + filename))
                    {
                        context.Response.ContentType = "text/html";
                        context.Response.Write("");
                        return;
                    }
                    context.Response.ContentType = "text/html";
                    context.Response.Write("http://" + context.Request.Url.Host + "/" + (System.Configuration.ConfigurationManager.AppSettings["SavePath"] + yearmonth + "/" + filename).Replace("\\", "/"));
                }
                else
                {
                    context.Response.ContentType = "text/html";
                    context.Response.Write("nofile");
                }
            }
            else
            {
                context.Response.ContentType = "text/html";
                context.Response.Write("nofile");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public string Ext(string filename) {
            string[] f = filename.Split('.');
            return "."+f[f.Length - 1].ToLower(); ;
        }
        //真正是否真的为图片  
        public static bool IsAllowedExtension(string  hifile)
        {
            FileStream fs = new FileStream(hifile, FileMode.Open, FileAccess.Read);
            BinaryReader r = new BinaryReader(fs);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = r.ReadByte();
                fileclass = buffer.ToString();
                buffer = r.ReadByte();
                fileclass += buffer.ToString();
            }
            catch { }
            r.Close();
            fs.Close();
            //说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar,|| fileclass=="13780"||fileclass=="6677"  
            if (fileclass == "255216" || fileclass == "7173" || fileclass == "13780")
            {
                return true;
            }
            else
            {
                return false;
            }
        }  
    }
}